﻿using System;
using RStein.Posterous.API;
using RStein.PosterousReader.Common;
using RStein.PosterousReader.WP.HostServices;
using RStein.PosterousReader.Common.ViewModelsHelpers;
using System.Windows.Input;
using RStein.PosterousReader.WP.Extensions;

namespace RStein.PosterousReader.WP.ViewModels
{
  public class LoginViewModel :  PosterousViewModelBase
  {
    private string m_userPassword;
    private string m_userName;        
    private ICommand m_loginCommand;    

    public LoginViewModel(IPosterousApplication posterousApplication, INavigationService navigationService)
                         : base(posterousApplication, navigationService, String.Empty)
    {
      
      m_loginCommand = new DelegateCommand<Object>(handleLogin, 
                                                     (_) => ValidateData());

      TextChangedAction = () => RaisePropertyChangedEvent(() => LoginCommand);
      
    }


    public Action TextChangedAction
    {
      get;
      private set;
    }
    
       
    public ICommand LoginCommand
    {
      get
      {
        return m_loginCommand;
      }
    }
    
    [PersistentState]
    public virtual string UserName
    {
      get
      {
        return m_userName;
      }

      set
      {
        m_userName = value;
        RaisePropertyChangedEvent(() => UserName);
      }
    }

    #if DEBUG
    [PersistentState]
    #endif
    public virtual string UserPassword
    {
      get
      {
        return m_userPassword;
      }

      set
      {
        m_userPassword = value;
        RaisePropertyChangedEvent(() => UserPassword);
      }
    }
    
        
    public override bool ValidateData()
    {
      return (!String.IsNullOrEmpty(UserName) &&    
              (!String.IsNullOrEmpty(UserPassword)));
              
    }
   
    private void handleLogin(Object ignored)
    {
      if (!HasValidData)
      {
        return;
      }
      
      LastUsedUserName = UserName;
      LastUsedPassword = UserPassword;      
      NavigationService.Navigate(GlobalConstants.PAGE_POST_LIST_URI);
      
    }

    public override void Deactivate()
    {
      base.Deactivate();
      clearPassword();
    }
    
    public override void Activate()
    {
      PosterousApplication.Current.RemoveAllCachedPosterousAccounts();
    }

    protected override void DoInternalInit()
    {
      UserName = LastUsedUserName;      
    }

    private void clearPassword()
    {
      UserPassword = String.Empty;
    }
  }
}
